import { getTransfereeCount } from '@/api/user';
import { Message } from 'element-ui';
import ElMessage from '@/utils/message';

export default {
  methods: {
    selRoleType(curVal = [], item) {
      let val = null;
      if (item.onlyOneRole) {
        val = curVal.length ? [curVal.pop()] : [];
        ElMessage.warning('不可同时选择申请人与审批人进行交接！');
      } else {
        val = curVal;
      }
      this.$set(item, 'roleIds', val);
      item.transferContent.forEach(item => {
        item.ids = [];
      });
      const key = item.businessType === 15 ? item.formId : item.businessType;
      const tempRoleData = this.moduleRoleData[key].filter(ele => {
        return val.includes(ele.roleType);
      });
      let temp = tempRoleData.map(item => {
        return item.contents;
      });
      temp = this.flattenArr(temp);
      temp = this.removeDuplicate(temp);
      for (let i = 0; i < item.transferContent.length; i++) {
        for (let j = 0; j < temp.length; j++) {
          if (item.transferContent[i].status === temp[j].status) {
            const curItem = [item.transferContent[i], temp[j]];
            const obj = Object.assign({}, ...curItem);
            this.$set(item.transferContent, i, obj);
            break;
          }
        }
        if (!item.contentsIds.includes(item.transferContent[i].status)) {
          // 没勾选，则removeIds = 当前的ids
          item.transferContent[i].removeIds = item.transferContent[i].ids;
        } else {
          // 勾选了，需要去除因为切换角色而不存在的removeIds
          item.transferContent[i].removeIds = item.transferContent[i].removeIds.filter(cur => {
            return item.transferContent[i].ids.includes(cur);
          });
        }
      }
    },
    selContentId(val, item) {
      if (val) {
        // 选中,将removeIds置为空
        item.removeIds = [];
      } else {
        // 没选中,removeIds全部等于ids
        item.removeIds = item.ids;
      }
    },
    flattenArr(arr) {
      // 扁平化数组
      return [].concat(...arr.map(x => Array.isArray(x) ? this.flattenArr(x) : x));
    },
    removeDuplicate(arr) {
      // 去重
      const resArr = [];
      JSON.parse(JSON.stringify(arr)).forEach(row => {
        const newRow = resArr.find(v => v.status === row.status);
        if (newRow) {
          // ids直接去重
          newRow.ids = Array.from(new Set([...row.ids, ...newRow.ids]));
          // fieldInfo需要对里面的id去重
          row.fieldInfo = row.fieldInfo || [];
          newRow.fieldInfo = newRow.fieldInfo || [];
          const fieldData = [...row.fieldInfo, ...newRow.fieldInfo];
          let d = [];
          const hash = {};
          d = fieldData.reduce((item, next) => {
            hash[next.id] ? '' : (hash[next.id] = true && item.push(next));
            return item;
          }, []);
          newRow.fieldInfo = d;
        } else {
          resArr.push(row);
        }
      });
      return resArr;
    },
    formatData(res, item, that) {
      item.roleData = res.data;
      // 处理数据
      const data = res.data;
      // 每个模块,对应赋值
      const key = item.businessType === 15 ? item.formId : item.businessType;
      that.moduleRoleData[key] = data;
      const { defaultRoleId } = item;
      let temp = data.filter(el => {
        return defaultRoleId ? defaultRoleId.includes(el.roleType) : true;
      }).map(item => {
        return item.contents;
      });
      temp = that.flattenArr(temp);
      temp = that.removeDuplicate(temp);
      for (let i = 0; i < item.transferContent.length; i++) {
        for (let j = 0; j < temp.length; j++) {
          if (item.transferContent[i].status === temp[j].status) {
            const curItem = [item.transferContent[i], temp[j]];
            const obj = Object.assign({}, ...curItem);
            // item.transferContent[i] = obj;
            this.$set(item.transferContent, i, obj);
            break;
          }
        }
      }
      item.contentsIds = item.transferContent.map(ele => {
        return ele.status;
      });
      item.roleIds = defaultRoleId || item.roles.map(ele => {
        return ele.value;
      });
    },
    executePromise(arr) {
      arr.reduce((pre, next, index, carr) => {
        return pre.then(next);
      }, Promise.resolve());
    },
    createPromise(item, isCustom = false) {
      const that = this;
      return (resolve, reject) =>
        new Promise((resolve, reject) => {
          const params = {
            handoverId: isCustom ? that.handoverId : that.dataForm.handoverId,
            businessType: item.businessType
          };
          isCustom && (params.formId = item.formId);
          if ([7, 8].includes(item.businessType)) {
            params.transfereeId = that.dataForm.byTransferId;
          }
          getTransfereeCount(params).then(res => {
            that.formatData(res, item, that);
            resolve();
          }).catch(err => {
            console.log(err);
            reject();
          });
        });
    },
    validate(isCustom = false) {
      const data = isCustom ? this.customFlowData : this.tableData;
      const mul = isCustom ? this.mulIds : this.multipleSelection;
      const formkey = isCustom ? 'formId' : 'businessType';
      const namekey = isCustom ? 'name' : 'module';
      const formName = isCustom ? '自定义表单' : '固定表单';
      // 已勾选模块
      const temp = data.filter(item => {
        return mul.includes(item[formkey]);
      });
      temp.forEach(item => { item.message = ''; });
      // 没选择模块后的内容或角色,弹出提示
      let message = '';
      temp.forEach(item => {
        if (item.roleIds.length === 0 || item.contentsIds.length === 0) {
          item.message = `请选择${formName}【${item[namekey]}】的`;
          item.message += item.contentsIds.length === 0 ? ' 交接内容' : '';
          item.message += item.roleIds.length === 0 ? ' 交接角色' : '';
        }
      });
      message = temp.filter(item => {
        return !!item.message;
      }).map(item => {
        return '<span style="display:inline-block;ling-height: 20px;margin-bottom:6px">' + item.message + '</span>';
      }).join('<br/>');
      if (message !== '') {
        Message({
          type: 'warning',
          dangerouslyUseHTMLString: true,
          message: message
        });
        return true;
      } else {
        return false;
      }
    }
  }
};
